package jbewordsrearrange;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JBEWordsReArrange {

	String text;
	BufferedReader br;
	Matcher matcher;
	Pattern pattern;
	static int x = 0;
	static String[] arr_nhap = new String[x];

	void inputText() throws IOException {
		System.out.println("Enter your text:");
		br = new BufferedReader(new InputStreamReader(System.in));
		text = br.readLine();
	}

	void countWord() {
		filterWords();
		while (matcher.find()) {
			x = x + 1;
		}
		System.out.println(x);
	}

	void filterWords() {
		pattern = Pattern.compile("\\S+");
		matcher = pattern.matcher(text);
	}

	void arrangeWords() {
		for (int a = 0; a < arr_nhap.length; a++) {
			for (int b = 0; b <= a; b++) {
				int i = 0;
				if ((int) (arr_nhap[a].charAt(0)) < (int) arr_nhap[b].charAt(0)) {
					String temp = null;
					temp = arr_nhap[a];
					arr_nhap[a] = arr_nhap[b];
					arr_nhap[b] = temp;
				} else if ((int) (arr_nhap[a].charAt(i)) == (int) arr_nhap[b]
						.charAt(i)) {
					for (i = 0; i < arr_nhap[a].length(); i++) {
						if ((int) (arr_nhap[a].charAt(i)) < (int) arr_nhap[b]
								.charAt(i)) {
							String temp = null;
							temp = arr_nhap[a];
							arr_nhap[a] = arr_nhap[b];
							arr_nhap[b] = temp;
						}
						if ((int) (arr_nhap[a].charAt(i)) == (int) arr_nhap[b]
								.charAt(i)) {

						}
					}
				}
			}
		}
	}

	void outputText() {
		System.out.println("Output text:");
		for (int i = 0; i < arr_nhap.length; i++) {
			System.out.print(arr_nhap[i] + " ");
		}
	}

	void process() throws IOException {
		inputText();
		countWord();	
		filterWords();
		arr_nhap = new String[x];	
		pattern = Pattern.compile("\\S+");
		matcher = pattern.matcher(text);
		System.out.println("Input Text:");
		for (int i = 0; matcher.find(); i++) {
			System.out.print(matcher.group() + " ");
			arr_nhap[i] = matcher.group();
		}
		System.out.println("");
		arrangeWords();
		outputText();
	}

	public static void main(String[] args) throws IOException {
		JBEWordsReArrange run = new JBEWordsReArrange();					
		run.process();				
	}

}
